<!-- 用于commonEdit内部的编辑弹窗 -->

<template>
  <div class="sub-edit-main">
    <div class="sub-edit-container">
      <div class="sub-edit-close">
        <el-button icon="el-icon-close" circle type="danger" size="mini" @click="close"></el-button>
      </div>
      <div class="sub-edit-operation">
        <div class="sub-edit-title">{{label}}</div>
        <div>
          <el-button v-if="!disabled" size="mini" type="primary" @click="submit">保存</el-button>
          <el-button size="mini" @click="close">取消</el-button>
        </div>
      </div>
      <el-form class="sub-edit-form" ref="form" :model="formData" label-width="140px" size="small" status-icon>
        <el-form-item style="item.type == 'empty'?'visibility: hidden':''" class="sub-edit-form-item" v-for="(item, index) of items" :label="item.name" :key="index" :required="item.required">
          <el-input v-if="item.type == 'empty'" class="sub-edit-hidden"/>
          <!-- 单个输入 -->
          <el-input :disabled="disabled || item.disable" v-if="item.type == 'text'" v-model="formData[item.key]" :placeholder="item.placeholder"></el-input>
          <!-- 一行多个输入 -->
          <el-row v-if="item.type=='multi-text'">
            <el-col :span="textItem.span" v-for="(textItem,index) of item.texts" :key="index">
              <el-input :disabled="disabled || textItem.disable" :placeholder="textItem.placeholder" v-model="formData[textItem.key]">
                <template v-if="textItem.name" slot="append">{{textItem.name}}</template>
              </el-input>
            </el-col>
          </el-row>
          <!-- 带checkbox输入 -->
          <el-row v-if="item.type=='checktext'" type="flex" justify="space-between" style="width: 100%;">
            <el-col :span="11">
              <el-input :disabled="disabled || item.disable || formData[item.key + 'checkbox']" v-model="formData[item.key]" :placeholder="item.placeholder"></el-input>
            </el-col>
            <el-col v-if="!disabled" :span="12">
              <el-checkbox :disabled="disabled || item.disable" v-model="formData[item.key + 'checkbox']" :label="item.checkname" name="type"></el-checkbox>
            </el-col>
          </el-row>
          <!-- 搜索的输入框 -->
          <el-input v-if="item.type=='search'" :disabled="disabled || item.disable" readonly :placeholder="item.placeholder" v-model="formData[item.key]">
            <el-button v-if="!disabled && !item.disable" slot="append" icon="el-icon-search" @click="search(item)"></el-button>
          </el-input>
          <el-input type="textarea" :disabled="disabled || item.disable" v-if="item.type == 'textarea'" v-model="formData[item.key]" :placeholder="item.placeholder"></el-input>
          <!-- 单选 -->
          <el-select loading-text="加载中" :disabled="disabled || item.disable" class="single" v-if="item.type == 'single-select'" v-model="formData[item.key]" @change="((el)=>{selectChange(el,item.key)})" placeholder="请选择" @focus="getSelectOption(item)">
            <el-option v-for="(option, index) of item.options" :key="index" :label="option.name" :value="option.value"></el-option>
          </el-select>
          <!-- 一行多个选择 -->
          <div v-if="item.type=='multi-select'" style="display: flex; flex-direction:row; width: 100%;flex-wrap: wrap;">
            <template v-for="(options, index) of item.optionss">
              <div style="width: 115px;display: flex;">
                <el-select style="width: 85px;" loading-text="加载中" :disabled="disabled || options.disable" class="single" v-model="formData[options.key]" @change="((el)=>{selectChange(el,options.key)})" placeholder="请选择" @focus="getSelectOption(options)">
                  <el-option v-for="(option, index) of options.options" :key="index" :label="option.name" :value="option.value"></el-option>
                </el-select>
                <div style="width: 30px;">{{['省', '市', '区县'][index]}}</div>
              </div>
            </template>
          </div>
          <!-- checkbox -->
          <el-checkbox :disabled="disabled || item.disable" name="type" v-if="item.type=='checkbox'" v-model="formData[item.key]" :checked="formData[item.key] == 1 || formData[item.key] == true"></el-checkbox>
          <!-- 坐标 -->
          <template v-if="item.type=='location'">
            <el-row>
              <el-col :span="1">
                X
              </el-col>
              <el-col :span="23">
                <el-input :disabled="disabled || item.disable" v-model="formData[item.key1]" placeholder=""></el-input>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="1">
                Y
              </el-col>
              <el-col :span="23">
                <el-input :disabled="disabled || item.disable" v-model="formData[item.key2]" placeholder=""></el-input>
              </el-col>
            </el-row>
          </template>
        </el-form-item>
        <div style="font-size: 13px; color: red;">
          {{tips}}
        </div>
        <template v-if="showAddress">
          <el-divider class="divider"></el-divider>
          <el-row v-if="pageType==1" style="font-size: 15px;font-weight: 500; margin-top: 10px">
            【门店名称】{{formData.retailName}}【门店地址】{{formData.province}},{{formData.cityName}},{{formData.adminCity}},{{formData.deAddress}}
          </el-row>
        </template>
        <el-row style="width: 100%; padding: 20px; padding-bottom: 0;">
          <el-radio-group v-model="tabIdx" size="small" @change="loadSubData">
            <el-radio-button v-for="(item, index) of tabItems" v-if="item.showPage" :key="index" :label="index">{{item.name}}</el-radio-button>
          </el-radio-group>
        </el-row>
        <template v-for="(tabItem, index) of tabItems">
          <div v-if="tabIdx==index" style="padding: 5px; border: 1px solid #b0b0b0; width: 100%; display: flex; flex-wrap: wrap; flex-direction: row; overflow: hidden;">
          <div v-if="tabItem.type=='table' && tabItem.showPage" style="width: 100%; display: block; overflow: auto;">
            <el-table show-header :data="tabItem.data" border stripe header-cell-class-name="table-head-cell" cell-class-name="table-head-cell" highlight-current-row>
              <template v-for="(header, index) of tabItem.headers">
                <el-table-column v-if="header.prop=='operate'" fixed="right" align='center' label="操作">
                  <template slot-scope="scope">
                    <el-popconfirm v-for="(operate, index) of header.operates" :key="index" confirmButtonText='确定' cancelButtonText='不用了' icon="el-icon-info" iconColor="red" title="'确定要【' + operate.name +'】吗？'" @onConfirm="operate.action(scope.row)">
                      <el-button slot="reference" type="text" size="small">operate.name</el-button>
                    </el-popconfirm>
                  </template>
                </el-table-column>
                <el-table-column v-else align='center' :key="index" :label="header.label"
                                  :min-width="getMaxLength(tabItem.data, header.prop) < (header.label.length * 13 + 20)?(header.label.length * 13 + 20):getMaxLength(tabItem.data, header.prop)">
                  <template slot-scope="scope">
                    <span v-if="typeof scope.row[header.prop] == 'number' && (scope.row[header.prop] == 0 || scope.row[header.prop] == 1)">{{ scope.row[header.prop] == 0 ? "否":"是" }}</span>
                    <span v-else>{{scope.row[header.prop]}}</span>
                  </template>
                </el-table-column>
              </template>
            </el-table>
          </div>
          <template v-if="tabItem.type=='text' && tabItem.showPage">
            <el-form-item v-for="(text, index) of tabItem.texts" :key="index + '_text'" class="form-item" :label="text.label">
              <el-input v-if="text.type=='text'" :disabled="text.disable" v-model="formData[text.key]" :placeholder="text.placeholder"></el-input>
              <el-input v-if="text.type=='search'" :disabled="text.disable" readonly v-model="formData[text.key]">
                <el-button v-if="!text.disable" slot="append" icon="el-icon-search" @click="search(text)"></el-button>
              </el-input>
            </el-form-item>
          </template>
        </div>
        </template>
      </el-form>
    </div>
  </div>
</template>

<script>
import http from '../../api/http'
import Tools from "@/util/Tools.js";
export default {
  props: {
    disabled: Boolean, // 是否不可编辑
    tips: String,
    showAddress: false, // 是否显示地址
    originalData: {
      type: Object,
      default () {
        return null
      }
    },
    tabItems: Array,
    label: {
      type: String,
      default: ''
    },
    pageType: {
      type: Number,
      default() {
        return -4
      }
    },
    items: {
      type: Array,
      default () {
        return []
      }
    },
  },
  data() {
    return {
      tabIdx: 0,
      formData: this.originalData ? this.originalData : {},
    }
  },
  methods: {
    selectChange(itemId, key) {
      for (let idx in this.conItems) {
        let item = this.items[idx]
        if (item.type == 'single-select' || item.type == 'multi-select') {
          if (item.key == 'city' && item.key == key) {
            if (key == 'province') {
              this.formData.physicalCity = null
              this.formData.adminCity = null
              this.formData.fkCityType = null
              item.optionss[1].options = []
              item.optionss[2].options = []
            } else if (key == 'physicalCity') {
              item.optionss[2].options = []
              this.formData.adminCity = null
              this.formData.fkCityType = null
            }
          } else if (item.key == key) {
            this.formData[item.vkey] = itemId
          }
        } else {
          continue
        }
      }
      if (key == 'adminCity') {
        let item = this.$select
        if (item) {
          for (let idx in item.options) {
            let option = item.options[idx]
            if (option.adminCity == itemId) {
              let data = Object.assign({}, this.formData)
              data.fkCityType = option.fkCityType
              data.cityTypeName = option.cityTypeName
              this.formData = data
              break;
            }
          }
        }
      }
    },
    search(item) {
      this.$emit('search', item, (obj) => {
        // 已绑定的对象不允许动态添加属性，添加了也不会生成setter和getter
        let data = Object.assign({}, this.formData)
        data = Object.assign(data, obj)
        this.formData = data
        // 供货方式
        if (this.formData.fkDealerType != null) {
          Tools.getDealerType(data=>{
            let items = data.list.filter(item => item.pkid == this.formData.fkDealerType)
            if (items.length <= 0) {
              this.$set(this.formData, 'typeName', null)
              this.$set(this.formData, 'fkDealerType', null)
            } else {
              this.$set(this.formData, 'typeName', items[0].typeName)
            }
          })
        }
        if (this.formData.fkDealerType1 != null) {
          Tools.getDealerType(data=>{
            let items = data.list.filter(item => item.pkid == this.formData.fkDealerType1)
            if (items.length <= 0) {
              this.$set(this.formData, 'typeName', null)
              this.$set(this.formData, 'fkDealerType1', null)
            } else {
              this.$set(this.formData, 'typeName', items[0].typeName)
            }
          })
        }
      })
    },
    getSelectOption(item) {
      this.$select = item
      this.$emit('getSelectOption',item, this.formData)
    },
    submit() {
      this.$emit('submit', this.formData)
    },
    close() {
      this.$emit('close')
    },
    getMaxLength (arr, key) {
    return arr.reduce((acc, item) => {
      if (item[key]) {
        const str = item[key].toString()
        const upLetter = str.match(/[A-Z]/g)
        const upLetterLen = upLetter ? upLetter.length : 0
        const lowLetter = str.match(/[a-z]/g)
        const lowLetterLen = lowLetter ? lowLetter.length : 0
        const char = str.match(/[\u2E80-\u9FFF]/g)
        const charLen = char ? char.length - upLetterLen - lowLetterLen : 0
        const num = str.match(/\d|\./g)
        const numLen = num ? num.length : 0
        const otherLen = str.length - upLetterLen - lowLetterLen - charLen - numLen
        let calcLen = charLen * 1.0 + upLetterLen * 0.65 + numLen * 0.55 + lowLetterLen * 0.48 + otherLen * 0.8
        if (acc < calcLen) {
          acc = calcLen
        }
      }
      return acc
    }, 0) * 13 + 20
  },
    loadSubData(index) {
      if (this.originalData) {
        this.row = null
        if (!this.tabItems || !this.tabItems[index].url) { return }
        let params = {pageNum: this.page, pageSize: this.pageSize, pkid: this.originalData.pkid}
        http.get(this.tabItems[index].url, params).then(resp => {
          if (resp instanceof Array) {
            this.tabItems[index].data = resp
          } else {
            this.tabItems[index].data = resp.list
          }
        }, msg => {})
      }
    },
  },
  created() {
    // 特殊配置，后台传值字段名为mdmCode,页面字段值为mdmCode
    if (this.label === '查看原始门店信息'){
      for (let index = 0; index < this.items.length; index++) {
        const element = this.items[index]
        if (element.key === 'mdmCode'){
           element.key = 'mdmCode'
           break
        }
      }
      console.log('qwerty',this.items)
    }
    if (this.formData.fkVendor) {
      Tools.getVendor({fkVendor: this.formData.fkVendor}, resp=>{
        let data = Object.assign({}, this.formData)
        data.vendorCode = resp.vendorCode
        data.fkVendor = resp.pkid
        this.formData = data
      })
    }
    if (this.formData.fkPayLink) {
      Tools.getPaylink({fkPayLink: this.formData.fkPayLink}, resp=>{
        let data = Object.assign({}, this.formData)
        data.payLinkName = resp.payLinkName
        data.payLinkCode = resp.payLinkCode
        data.fkVendor = resp.pkid
        this.formData = data
      })
    }
    if (this.formData.fkAdminCity) {
      Tools.getAdminCityInfo({fkAdminCity: this.formData.fkAdminCity}, resp=>{
        let data = Object.assign({}, this.formData)
        data.cityTypeName = resp.cityTypeName
        data.fkCityType = resp.fkCityType
        data.adminCity = resp.adminCity
        this.formData = data

      })
    }
    // 设置默认显示
    Tools.getBussinessStatus(data=>{
      if (this.formData.businessStatus) {
        this.formData.businessStatus = data[0].dkey
        this.formData = Object.assign({}, this.formData)
      } else {
        let items = data.filter(item => item.dkey == this.formData.businessStatus)
        if (items.length <= 0) {
          this.formData.businessStatus = data[0].dkey
          this.formData = Object.assign({}, this.formData)
        }
      }
    })

    
    Tools.getCooperationStatus(data=>{
      if (this.formData.cooperationStatus) {
        this.formData.cooperationStatus = data[0].dkey
        this.formData = Object.assign({}, this.formData)
      } else {
        let items = data.filter(item => item.dkey == this.formData.cooperationStatus)
        if (items.length <= 0) {
          this.formData.cooperationStatus = data[0].dkey
          this.formData = Object.assign({}, this.formData)
        }
      }
    })
    Tools.getBuList(data=>{
      let items = data.filter(item => item.buName == this.formData.buName)
      if (items.length <= 0) {
        this.formData.buName = null
        this.formData.fkBu = null
      }
    })
    // 供货方式
    if (this.formData.fkDealerType != null) {
      Tools.getDealerType(data=>{
        let items = data.list.filter(item => item.pkid == this.formData.fkDealerType)
        if (items.length <= 0) {
          this.$set(this.formData, 'typeName', null)
          this.$set(this.formData, 'fkDealerType', null)
        } else {
          this.$set(this.formData, 'typeName', items[0].typeName)
        }
      })
    }
    if (!this.formData.destinationName) {
      Tools.getDestinations(data=>{
        let items = data.filter(item => item.pkid == this.formData.fkDestination1)
          if (items.length > 0) {
            this.formData.destinationName = items[0].destinationName
            this.formData = Object.assign({}, this.formData)
          } else {
            this.formData.destinationName = data[0].destinationName
            this.formData = Object.assign({}, this.formData)
          }
      })
    }
    this.loadSubData(0)
  }
}
</script>

<style lang="css" scoped>
.sub-edit-main {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
}
.sub-edit-container {
  position: relative;
  display: block;
  width: 80%;
  height: 60%;
  background: white;
  overflow: auto;
}
.sub-edit-title {
    font-size: 16px;
    font-weight: 600;
    color: #666666;
}
.sub-edit-operation {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    margin-top: 30px;
}
.sub-edit-close {
  position: fixed;
  margin: 0;
  width: 80%;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  background: red;
  z-index: 99;
}
.sub-edit-form {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    border: 1px solid #f2f2f2;
    padding: 5px 0;
}
.sub-edit-form-item {
    width: 46%;
    margin: 5px 2%;
}
/deep/.el-form-item__label {
    font-size: 12px;
    text-align: center;
}
/deep/.el-select.single {
    width: 100%;
}
.sub-edit-hidden {
  visibility: hidden;
}

.el-table {
  overflow: visible;
}

.divider {
  margin: 0;
}

/deep/.el-input.is-disabled .el-input__inner {
  cursor: text! important;
}

.form-item {
    width: calc(50% - 10px);
    margin: 5px 5px;
}

/deep/.el-form-item--mini.el-form-item, .el-form-item--small.el-form-item {
  margin-bottom: 0! important;
}

/deep/.el-form-item--small .el-form-item__label {
  height: 100%;
  padding: 0;
  margin-right: 5px;
  background: #f1f1f1;
  border: 1px solid #e7e7e7;
  display: flex;
  align-items: center;
  justify-content: center;
}
/deep/.el-form-item--small .el-form-item__content {
  padding: 10px 10px;
  border: 1px solid #e7e7e7;
  display: flex;
  flex-direction: row;
  align-items: center;
  height: 100%;
}

/deep/.el-radio-button {
  margin-left: 5px;
}
/deep/.el-radio-button:first-child {
  margin-left: 0;
}
/deep/.el-radio-button:first-child .el-radio-button__inner {
  border-radius: 0;
}

/deep/.el-radio-button:last-child .el-radio-button__inner {
  border-radius: 0;
}

/deep/.el-radio-button__inner {
  border-left: 1px solid #DCDFE6;
  font-weight: 600;
}

/deep/ .el-input.is-disabled .el-input__inner {
  color: #606266;
}

/deep/.el-button /deep/ span {
  display: inline-block;
}

</style>
